#include <iostream>
using std::cout;
using std::endl;
//单例：
//1.全局该类只有一个实例对象----需要保证构造函数不能被任意调用
//2.需要提供一个静态的函数，将创建出来的对象或者存在的对象暴露出去
//3.需要避免拷贝
//4.单例对象创建在堆区，会有new；也需要成对出现delete
class Singleton{
public:
    static Singleton * getInstance(){
        if(_pInstance == nullptr){
            _pInstance = new Singleton();
        }
        return _pInstance;
    }
    //需要去写这个destroy函数，需要手动调用
    //希望能够自动调用该函数
    static void destroy(){
        if(_pInstance){
            delete _pInstance;
            _pInstance = nullptr;
        }
    }
    void print(){
        cout << "Singleton::print()" << endl;
    }

    Singleton(const Singleton & rhs) = delete;
    Singleton & operator=(const Singleton & rhs) = delete;
private:
    Singleton(){}
    ~Singleton(){}
    static Singleton * _pInstance;
};
Singleton * Singleton::_pInstance = nullptr;


void test(){
    Singleton::getInstance()->print(); 
    Singleton * ps1 = Singleton::getInstance();
    Singleton * ps2 = Singleton::getInstance();
    //delete ps1;
    //delete ps2;
    Singleton::destroy();
    Singleton::destroy();
}

int main()
{
    test();
    return 0;
}

